import { Component, ChangeDetectorRef, ViewChild } from '@angular/core';
import { NavController, AlertController, Content,ViewController } from 'ionic-angular';
import Wechat from 'wechat-jssdk/lib/client';



import { WeChatApi } from '../../providers/wechatapi';
import { AppConfig } from '../../app/app.config';
import { Fun } from '../../providers/fun';
import { PubApi } from '../../providers/pubapi';


@Component({
  selector: 'page-log',
  templateUrl: 'log.html'
})
export class LogPage {
  @ViewChild(Content) content1: Content;　　//获取界面Content的实例对象
  profilePicture: any = { localId: [], serverId: [], localstr: [] };
  imgidlist: any = [];
  Situation: any;
  SupervisionWork: any;
  starttime:any;
   endtime:any;
  constructor(public navCtrl: NavController, public alertCtrl: AlertController, public fun: Fun, public changeref: ChangeDetectorRef,public viewCtrl: ViewController, public wechatapi: WeChatApi, public pubapi: PubApi) {
var sdate="",endate="";
var d=new Date();
var num:number=d.getMonth();
var m="";
if(num<9)
{
    m="0"+(num+1).toString();
}
else
{
   m=(num+1).toString();
}
var day:number=d.getDate();
var sday="";
var eday="";
if(day<10)
{
    sday="0"+(day).toString();
     eday="0"+(day).toString();
}
else
{
  sday=day.toString();
  eday=day.toString();
}

sdate=d.getFullYear()+"-"+m+"-"+sday;
endate=d.getFullYear()+"-"+m+"-"+eday;
this.starttime=sdate;
this.endtime=endate;

  } 

  ionViewWillEnter() {
    this.wechatapi.GetSign().subscribe((res) => {
      if (res && res.data) {
        var that = this;
        var config = {
          //前4个是微信验证签名必须的参数，第2-4个参数为类似上面 '/get-signature' 从node端获取的结果Wm3WZYTPz0wzccnW      'nonceStr': 'xxx','signature': 'xxx','timestamp': 'xxx',
          'appId': AppConfig.getWeChat().appid,
          'nonceStr': '',
          'signature': '',
          'timestamp': '',
          //下面为可选参数
          'success': function () {
            console.log('success');
            var w = this;
            if (!w.wx) {
              w.wx = (<any>window).wx;
            }

          }, //微信签名成功回调函数, 跟 'successCallback' 一样
          'error': function (err) {
            // var w = this;
            // var b = { nonceStr: w.config.nonceStr, signature: w.config.signature, timestamp: w.config.timestamp };
            // w.signSignature(b);
          }, //微信签名失败回调函数, 跟 'errorCallback' 一样
          'debug': true, //开启 debug 模式
          'jsApiList': ['getLocation', 'chooseImage', 'uploadImage', 'downloadImage'], //设置所有想要使用的微信jsapi列表, 默认值为 ['onMenuShareTimeline', 'onMenuShareAppMessage']，分享到朋友圈及聊天记录
          'customUrl': '' //自定义微信js链接
        };
        config.nonceStr = res.data.Noncestr;
        config.signature = res.data.Signature;
        config.timestamp = res.data.Timestamp;
        (<any>window).wechatObj = new Wechat(config);
      }
    });
  }
   dismiss() {
    this.viewCtrl.dismiss();
  }
  openOfficial(index: any) {
    if ((<any>window).wechatObj) {
      var that = this;
      this.wechatapi.GetSign().subscribe((ressg) => {
        (<any>window).wechatObj.wx.chooseImage({
          success: function (res) {

            that.profilePicture.localId = res.localIds;
            // images.localId = res.localIds;
            var i = 0, length = that.profilePicture.localId.length;

            function upload() {

              //上传图片
              (<any>window).wechatObj.wx.uploadImage({

                localId: that.profilePicture.localId[i],

                success: function (res1) {
                  i++;
                  (<any>window).Access_token=ressg.data.Access_token;
                  that.wechatapi.getimage(ressg.data.Access_token, res1.serverId).subscribe((wres) => {
                    var id = wres.data._id;
                    that.imgidlist.push(id);

                  });


                  if (index !== '' && that.profilePicture.localstr.length > 0) {
                    that.profilePicture.localstr[index] = res.localIds;
                    that.profilePicture.serverId[index] = res1.serverId;

                  } else {
                    that.profilePicture.localstr.push(res.localIds);
                    that.profilePicture.serverId.push(res1.serverId);

                  }



                  that.changeref.detectChanges();
                  that.content1.resize();
                  //下载图片
                  // (<any>window).wechatObj.wx.downloadImage({

                  //   serverId: res1.serverId, // 需要下载的图片的服务器端ID，由uploadImage接口获得
                  //   isShowProgressTips: 1, // 默认为1，显示进度提示
                  //   success: function (res2) {
                  //     // that.profilePicture.localstr.push(res2.localId);
                  //     // var localId = res2.localId; // 返回图片下载后的本地ID

                  //   }
                  // });
                },
                fail: function (res3) {
                  // alert(JSON.stringify(res3));
                  // alert('ImgISOK?');
                }
              });
            }
            if (i < length) {
              upload();
            }
            // alert('已选择 ' + res.localIds.length + ' 张图片');
          },
          fail: function (res3) {
           // alert(res3);
          }
        }
        );
      });
    }
    else {
    
      this.fun.showAlert("微信信息获取失败");
    }
  }
  advisesubmit() {
    var that = this;
    let loglist = {
      SupervisionUser:Fun.getcookie("name"),
      Situation: this.Situation,
      SupervisionWork: this.SupervisionWork,
      imgid: this.imgidlist,

    };
    //  alert(advise.localId);
    if (this.Situation == undefined) {
      this.fun.showlogAlert("日志", "请填写日志标题");
    }
    else
      if (this.SupervisionWork == undefined) {
        this.fun.showlogAlert("日志", "请填写日志内容");
      }
      else {
        
        this.pubapi.post("WorkLog/MobileCreate", loglist, function (res) {
          let result = res.data;
          that.fun.showlogAlert("日志", res.message);

        })
        this.imgidlist.forEach((id)=>{
            that.pubapi.get("webchat/GetPictureDownloadUrl?access_token="+(<any>window).Access_token+"&media_id="+id+"", function (res) {
          let result = res.data;
         })
        })
       }
  }
}
